/**
 * JimBot - Java IM Bot
 * Copyright (C) 2006-2009 JimBot project
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package faac.util;

import java.io.*;
import java.util.*;

import faac.table.UserPreference;

/**
 * Основные настройки бота
 * 
 * @author Prolubnikov Dmitry
 */
public class MainProps {
        private static Properties appProps;
    public static final String VERSION = "v.0.4.0 pre 4 (06/07/2009)";
//    public static final int VER_INT = 18;
//    public static final String VER_DESC ="test version";
//    private static int ver_no = 0;
//    private static long ver_last_read = 0;
//    private static String ver_desc = "";
//    public static final String VER_DESC = "Поправлена работа при условии нестабильного соединения с MySQL;" +
//    		"Кеширование скриптов;" +
//    		"";
    public static final String PROG_TITLE = "jImBot";
    public static final String PROPS_FILE = "./chat.xml";
//    public static final String ENCODING = "windows-1251";

//    private static Properties langProps;
//    private static boolean isLoaded = false;
//    private static Vector servers = new Vector();
    private static String currentServer = "";
    private static int currentPort = 0;
//    private static int countServer = 0;
    private static HashSet<String> ignor;

    /** Creates a new instance of MainProps */
    public MainProps() {
    }
    
    public static final void setDefault() {
        appProps = new Properties();


//        setStringProperty("main.Socks5ProxyHost","");
//        setStringProperty("main.Socks5ProxyPort","");
//        setStringProperty("main.Socks5ProxyUser","");
//        setStringProperty("main.Socks5ProxyPass","");
        setIntProperty("srv.servicesCount",1);
        setStringProperty("srv.serviceName0","ChatBot");
        setStringProperty("srv.serviceType0","chat");
        setIntProperty("http.delay",10);
        setStringProperty("icq.serverDefault","login.icq.com");
        setIntProperty("icq.portDefault",5190);
        setStringProperty("http.user","admin"); // юзер для админки
        setStringProperty("http.pass","admin"); // пароль для доступа в админку
        setIntProperty("http.port",8888);// порт
        setBooleanProperty("log.service", true);


    }
    
    public static UserPreference[] getUserPreference(){
        UserPreference[] p = {
            new UserPreference(UserPreference.CATEGORY_TYPE,"main", "Основные настройки",""),
            new UserPreference(UserPreference.BOOLEAN_TYPE,"log.service","Включить/Выключить посервисное логирирование",getBooleanProperty("log.service")),
            new UserPreference(UserPreference.INTEGER_TYPE,"http.delay","Время жизни HTTP сессии",getIntProperty("http.delay")),
 //           new UserPreference(UserPreference.CATEGORY_TYPE,"main", "Настройки прокси",""),
 //           new UserPreference(UserPreference.STRING_TYPE,"main.Socks5ProxyHost","Прокси хост",getStringProperty("main.Socks5ProxyHost")),
 //           new UserPreference(UserPreference.STRING_TYPE,"main.Socks5ProxyPort","Прокси порт",getStringProperty("main.Socks5ProxyPort")),
 //           new UserPreference(UserPreference.STRING_TYPE,"main.Socks5ProxyUser","Прокси пользователь",getStringProperty("main.Socks5ProxyUser")),
 //           new UserPreference(UserPreference.STRING_TYPE,"main.Socks5ProxyPass","Прокси пароль",getStringProperty("main.Socks5ProxyPass")),
           new UserPreference(UserPreference.CATEGORY_TYPE,"bot", "Настройки бота",""),
            new UserPreference(UserPreference.STRING_TYPE,"icq.serverDefault","ICQ Сервер 1",getStringProperty("icq.serverDefault")),
            new UserPreference(UserPreference.INTEGER_TYPE,"icq.portDefault","ICQ Порт 1",getIntProperty("icq.portDefault")),
            new UserPreference(UserPreference.CATEGORY_TYPE,"http", "настройки админки",""),
            new UserPreference(UserPreference.STRING_TYPE,"http.user","юзер для админки",getStringProperty("http.user")),
            new UserPreference(UserPreference.STRING_TYPE,"http.pass","пароль для доступа в админку",getStringProperty("http.pass")),
            new UserPreference(UserPreference.INTEGER_TYPE,"http.port","порт для домтупа к админке",getIntProperty("http.port"))

        };
        return p;
    }
    
    /**
     * Загружает игнор-лист из файла
     */
    public static void loadIgnorList(){
    String s;
    ignor = new HashSet<String>();
    try{
    BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("ignore.txt"),"windows-1251"));
    while (r.ready()){
    s = r.readLine();
    if(!s.equals("")){
    ignor.add(s);
    }
    }
    r.close();
    } catch (Exception ex){
    ex.printStackTrace();
    }
    }
     /**
     * УИН в игноре?
     * @param uin
     * @return
     */
    public static boolean isIgnor(String uin){
    	if(ignor==null) return false;
    	return ignor.contains(uin);
    }
    
    public static Properties getProps(){
        return appProps;
    }
    
    public static int getServicesCount(){
    	return getIntProperty("srv.servicesCount");
    }
    
    public static String getServiceName(int i){
    	return getStringProperty("srv.serviceName"+i);
    }
    
    public static String getServiceType(int i) {
    	return getStringProperty("srv.serviceType"+i);
    }
    
    public static int addService(String name, String type){
    	int c = getServicesCount();
    	setIntProperty("srv.servicesCount", c+1);
    	setStringProperty("srv.serviceName"+c, name);
    	setStringProperty("srv.serviceType"+c, type);
    	return c;
    }
    
    public static void delService(String name) {
    	// Сдвигаем элементы после удаленного на его место
    	boolean f = false;
    	for(int i=0; i<(getServicesCount()-1); i++){
    		if(getServiceName(i).equals(name))
    			f = true;
    		if(f){
    			setStringProperty("srv.serviceName"+i, getServiceName(i+1));
    			setStringProperty("srv.serviceType"+i, getServiceType(i+1));
    		}
    	}
    	//Удаляем самый последний элемент
    	appProps.remove("srv.serviceName"+(getServicesCount()-1));
    	appProps.remove("srv.serviceType"+(getServicesCount()-1));
    	setIntProperty("srv.servicesCount", getServicesCount()-1);
    }
    
    
    public static String getServer() {
            currentServer = getStringProperty("icq.serverDefault");
        return currentServer;
    }
    
    public static int getPort(){
        if(currentPort==0)
            currentPort = getIntProperty("icq.portDefault");
        return currentPort;
    }
    

     public static String getAbout(){
        return PROG_TITLE + " " + VERSION + "\n(c) Spec, 2006-2009\n" +
                "Поддержка проекта: http://jimbot.ru";
    }
    
public static final   void load(  ) {
        File file = new File(PROPS_FILE);
        setDefault();
        loadIgnorList();
        try {
            FileInputStream fi = new FileInputStream(file);
            appProps.loadFromXML(fi);
            fi.close();
            Log.getDefault().info("загруза файла настроек: "+ PROPS_FILE);
        } catch (Exception ex) {
            Log.getDefault().error("ОШИБКА загрузки файла настроек: "+ PROPS_FILE);}
    } 



    

    public static final void save() {
        File file = new File(PROPS_FILE);
        try {
            FileOutputStream fo = new FileOutputStream(file);
            appProps.storeToXML(fo, "jImBot properties");
            fo.close();
            Log.getDefault().info("сохранение файла настроек: "+ PROPS_FILE);
        } catch (Exception ex) {
            Log.getDefault().error("ошибка при сохранении файла настроек: "+ PROPS_FILE);
        }
    }
    

    public static void registerProperties(Properties _appProps) {
        appProps = _appProps;
    }
    
    public static String getProperty(String key) {
        return appProps.getProperty(key);
    }
    
    public static String getStringProperty(String key) {
        return appProps.getProperty(key);
    }
    
    public static String getProperty(String key, String def) {
        return appProps.getProperty(key,def);
    }
    
    public static void setProperty(String key, String val) {
        appProps.setProperty(key,val);
    }
    
    public static void setStringProperty(String key, String val) {
        appProps.setProperty(key,val);
    }
    
    public static void setIntProperty(String key, int val) {
        appProps.setProperty(key,Integer.toString(val));
    }
    
    public static void setBooleanProperty(String key, boolean val) {
        appProps.setProperty(key, val ? "true":"false");
    }
    
    public static int getIntProperty(String key) {
        return Integer.parseInt(appProps.getProperty(key));
    }
    
    public static boolean getBooleanProperty(String key) {
        return Boolean.valueOf(appProps.getProperty(key)).booleanValue();
    }







    /**
     * Авто создание log4j.PROPERTIES для заданного сервиса
     * @param name
     */

    public static void AddLogProperties (String name){
    try {
    String config = Log.Log4jProperties;
    config = config.replace("$SERVICE", name);
    OutputStreamWriter NewFile = new OutputStreamWriter( new FileOutputStream( "./services/" + name + "/log4j.PROPERTIES", true ), "windows-1251" );
    NewFile.write( config );
    NewFile.close();
    }
    catch ( Exception ex )
    {
    Log.getLogger(name).error( "Ошибка создания файла \"log4j.PROPERTIES\" " , ex );
    }
    }




           /**
     * Порт http для админки
     * @return
     */
    public static int getHTTPPort() {
return getIntProperty("http.port");
}









}
